Implementing Classes and Objects Through Practical Examples in Java
Course: Core Java Training
Topic: Implementing Classes and Objects Through Practical Examples
Course Link: Core Java Training Course
Demo Link: Register for a Free Course Demo
Website: JustAcademy
1. Introduction to Classes and Objects
Classes and objects are fundamental concepts of Object-Oriented Programming (OOP) in Java. They help developers organize code into reusable structures that represent real-world entities, such as students, employees, bank accounts, products, and vehicles.
A class defines the structure and behavior of an entity, while an object is an instance of that class. A class specifies the data an object can store and the operations it can perform.
For example, a Student class may define a student's name, roll number, and marks. Individual Student objects can represent different students, each with their own values.
Learning Objectives
- Understand the difference between classes and objects.
- Define classes with fields, constructors, and methods.
- Create objects using the
new keyword.
- Access object fields and methods.
- Use constructors to initialize object data.
- Apply encapsulation to protect object state.
- Implement practical Java programs using classes and objects.
- Identify common errors and follow object-oriented programming best practices.
2. What Is a Class in Java?
A class is a blueprint or template used to create objects. It defines the fields, constructors, and methods that its objects can have.
A class declaration uses the class keyword followed by the class name and a pair of braces.
Basic Syntax
class ClassName {
// Fields
// Constructors
// Methods
}
Example: Defining a Book Class
class Book {
String title;
String author;
double price;
void displayDetails() {
System.out.println("Title: " + title);
System.out.println("Author: " + author);
System.out.println("Price: " + price);
}
}
In this example, Book is a class. It contains three fields and one method. The fields represent the book's data, while the method displays that data.
Important Components of a Class
| Component |
Purpose |
Example |
| Class name |
Identifies the class. |
Book |
| Field |
Stores object data. |
String title; |
| Constructor |
Initializes an object when it is created. |
Book() |
| Method |
Defines an operation or behavior. |
displayDetails() |
| Object |
Represents an instance of a class. |
new Book() |
3. What Is an Object in Java?
An object is a runtime instance of a class. It has identity, state, and behavior.
- Identity: Distinguishes one object from another.
- State: The data stored in its fields.
- Behavior: The operations it performs through methods.
For example, two Book objects may have different titles and prices even though they are created from the same Book class.
Creating an Object
Book firstBook = new Book();
This statement declares a reference variable named firstBook and assigns it a reference to a newly created Book object.
Understanding the Statement
Book is the reference type.
firstBook is the reference variable.
new creates a new object.
Book() invokes the constructor.
In Java, an object is generally created with new, although objects can also be obtained through other mechanisms, such as factory methods and deserialization.
4. Practical Example 1: Creating and Using Student Objects
Consider a school application that needs to store student information. A Student class can represent a student and provide a method to display the student's details.
Java Program
class Student {
String name;
int rollNumber;
double marks;
void displayDetails() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: " + marks);
}
}
public class Main {
public static void main(String[] args) {
Student student1 = new Student();
student1.name = "Aarav";
student1.rollNumber = 101;
student1.marks = 88.5;
student1.displayDetails();
}
}
Output
Name: Aarav
Roll Number: 101
Marks: 88.5
Explanation
- The Student class defines the fields
name, rollNumber, and marks.
- The
main() method creates a Student object.
- The program assigns values to the object's fields.
- The
displayDetails() method prints the stored information.
Creating Multiple Objects
Student student1 = new Student();
student1.name = "Aarav";
student1.rollNumber = 101;
student1.marks = 88.5;
Student student2 = new Student();
student2.name = "Meera";
student2.rollNumber = 102;
student2.marks = 92.0;
student1.displayDetails();
student2.displayDetails();
Each object maintains its own instance field values. Updating student1.name does not change student2.name.
5. Initializing Objects with Constructors
A constructor is a special class member used to initialize an object when it is created. A constructor has the same name as the class and does not declare a return type.
Constructors help ensure that an object starts with meaningful values instead of requiring separate assignments after creation.
Example: Student Constructor
class Student {
String name;
int rollNumber;
double marks;
Student(String name, int rollNumber, double marks) {
this.name = name;
this.rollNumber = rollNumber;
this.marks = marks;
}
void displayDetails() {
System.out.println(name + " - " + rollNumber + " - " + marks);
}
}
public class Main {
public static void main(String[] args) {
Student student1 = new Student("Aarav", 101, 88.5);
Student student2 = new Student("Meera", 102, 92.0);
student1.displayDetails();
student2.displayDetails();
}
}
Output
Aarav - 101 - 88.5
Meera - 102 - 92.0
Understanding the this Keyword
The this keyword refers to the current object. In the constructor, this.name refers to the object's field, while name refers to the constructor parameter.
Using this makes the assignment clear when parameter names and field names are identical.
6. Practical Example 2: Employee Management
An employee management program can use an Employee class to store an employee's ID, name, and salary. Methods can display details and calculate an annual salary.
Java Program
class Employee {
int employeeId;
String name;
double monthlySalary;
Employee(int employeeId, String name, double monthlySalary) {
this.employeeId = employeeId;
this.name = name;
this.monthlySalary = monthlySalary;
}
double calculateAnnualSalary() {
return monthlySalary * 12;
}
void displayDetails() {
System.out.println("Employee ID: " + employeeId);
System.out.println("Name: " + name);
System.out.println("Monthly Salary: " + monthlySalary);
System.out.println("Annual Salary: " + calculateAnnualSalary());
}
}
public class Main {
public static void main(String[] args) {
Employee employee = new Employee(501, "Riya", 35000);
employee.displayDetails();
}
}
Output
Employee ID: 501
Name: Riya
Monthly Salary: 35000.0
Annual Salary: 420000.0
What This Example Demonstrates
- Grouping related employee data in one class.
- Initializing fields through a constructor.
- Defining a calculation method.
- Calling one method from another method of the same object.
- Reusing the same class to create employee records with different values.
7. Practical Example 3: Bank Account Class
A BankAccount class can represent an account with an account holder and a balance. It can provide methods for depositing and withdrawing money.
This example also introduces encapsulation. The balance is kept private so that code outside the class cannot change it directly.
Java Program
class BankAccount {
private String accountHolder;
private double balance;
BankAccount(String accountHolder, double initialBalance) {
if (initialBalance < 0) {
throw new IllegalArgumentException(
"Initial balance cannot be negative."
);
}
this.accountHolder = accountHolder;
this.balance = initialBalance;
}
void deposit(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException(
"Deposit amount must be positive."
);
}
balance += amount;
}
void withdraw(double amount) {
if (amount <= 0) {
throw new IllegalArgumentException(
"Withdrawal amount must be positive."
);
}
if (amount > balance) {
throw new IllegalArgumentException(
"Insufficient balance."
);
}
balance -= amount;
}
double getBalance() {
return balance;
}
void displayAccount() {
System.out.println("Account Holder: " + accountHolder);
System.out.println("Current Balance: " + balance);
}
}
public class Main {
public static void main(String[] args) {
BankAccount account = new BankAccount("Rohan", 5000);
account.deposit(1500);
account.withdraw(1000);
account.displayAccount();
}
}
Output
Account Holder: Rohan
Current Balance: 5500.0
Explanation
- The constructor initializes the account holder and starting balance.
- The
deposit() method adds a valid amount to the balance.
- The
withdraw() method checks the amount and available balance before subtracting it.
- The
getBalance() method provides controlled read access to the private balance.
- The
displayAccount() method displays account information.
Practical note: This is a learning example. Real financial systems require additional safeguards, such as precise monetary representations, transaction consistency, authorization, audit logging, and concurrency handling.
8. Practical Example 4: Product and Price Calculation
A product class can represent items in an online store. Each product can have a name, price, and quantity. A method can calculate the total cost of the selected quantity.
Java Program
class Product {
String productName;
double price;
int quantity;
Product(String productName, double price, int quantity) {
this.productName = productName;
this.price = price;
this.quantity = quantity;
}
double calculateTotal() {
return price * quantity;
}
void displayProduct() {
System.out.println("Product: " + productName);
System.out.println("Price: " + price);
System.out.println("Quantity: " + quantity);
System.out.println("Total: " + calculateTotal());
}
}
public class Main {
public static void main(String[] args) {
Product product = new Product("Keyboard", 1200, 3);
product.displayProduct();
}
}
Output
Product: Keyboard
Price: 1200.0
Quantity: 3
Total: 3600.0
Key Learning Points
- Product information is grouped into a single object.
- The constructor initializes the product's state.
- The calculation method can be reused whenever the total is needed.
- Separate Product objects can represent different items.
9. Practical Example 5: Rectangle Area and Perimeter
Mathematical objects can also be represented using classes. A Rectangle class can store length and width and calculate area and perimeter.
Java Program
class Rectangle {
double length;
double width;
Rectangle(double length, double width) {
if (length <= 0 || width <= 0) {
throw new IllegalArgumentException(
"Length and width must be positive."
);
}
this.length = length;
this.width = width;
}
double calculateArea() {
return length * width;
}
double calculatePerimeter() {
return 2 * (length + width);
}
}
public class Main {
public static void main(String[] args) {
Rectangle rectangle = new Rectangle(10, 5);
System.out.println("Area: " + rectangle.calculateArea());
System.out.println("Perimeter: " + rectangle.calculatePerimeter());
}
}
Output
Area: 50.0
Perimeter: 30.0
Formulas Used
| Calculation |
Formula |
Example |
| Area |
Length × Width |
10 × 5 = 50 |
| Perimeter |
2 × (Length + Width) |
2 × (10 + 5) = 30 |
10. Instance Variables and Local Variables
Variables can be declared in different locations depending on their purpose. Understanding the difference between instance variables and local variables is important when implementing classes.
| Feature |
Instance Variable |
Local Variable |
| Declaration |
Inside a class, outside methods and constructors. |
Inside a method, constructor, or block. |
| Purpose |
Stores object state. |
Stores temporary data for an operation. |
| Lifetime |
Associated with the object's lifetime. |
Available within its declared scope. |
| Default values |
Receives a default value if not explicitly initialized. |
Must be definitely assigned before use. |
| Example |
private int age; |
int result = 10; |
Example
class Counter {
int count = 0; // Instance variable
void increment() {
int step = 1; // Local variable
count = count + step;
}
}
Each Counter object has its own count field. The local variable step is created for use during the method execution.
11. Accessing Object Fields and Methods
For accessible members, the dot operator (.) is used to access an object's fields and methods through its reference.
Example
class Car {
String brand;
void start() {
System.out.println(brand + " is starting.");
}
}
public class Main {
public static void main(String[] args) {
Car car = new Car();
car.brand = "Toyota";
car.start();
}
}
Output
Toyota is starting.
In this example, car.brand accesses the field and car.start() calls the method. If a field is declared private, it cannot be accessed directly from outside its declaring class; controlled methods can be used instead.
12. Encapsulation in Classes and Objects
Encapsulation means keeping data and related behavior together while controlling how internal data is accessed or modified. In Java, it is commonly implemented by declaring fields as private and exposing appropriate public methods.
Example: Encapsulated Person Class
class Person {
private String name;
private int age;
Person(String name, int age) {
setName(name);
setAge(age);
}
public String getName() {
return name;
}
public void setName(String name) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException(
"Name cannot be empty."
);
}
this.name = name;
}
public int getAge() {
return age;
}
public void setAge(int age) {
if (age < 0) {
throw new IllegalArgumentException(
"Age cannot be negative."
);
}
this.age = age;
}
}
Benefits of Encapsulation
- Protects fields from uncontrolled external modification.
- Allows validation before data is updated.
- Improves maintainability by hiding implementation details.
- Provides a clear interface for using objects.
- Helps maintain valid object state.
13. Class Members: Instance and Static
Instance members belong to individual objects. Static members belong to the class itself and are shared at the class level.
Example
class Employee {
String name;
static String company = "ABC Technologies";
Employee(String name) {
this.name = name;
}
void display() {
System.out.println(name + " works at " + company);
}
}
public class Main {
public static void main(String[] args) {
Employee employee1 = new Employee("Aman");
Employee employee2 = new Employee("Sara");
employee1.display();
employee2.display();
System.out.println(Employee.company);
}
}
Output
Aman works at ABC Technologies
Sara works at ABC Technologies
ABC Technologies
The name field is different for each Employee object, whereas the static company field is shared by the class. Static members can be accessed using the class name, as shown by Employee.company.
14. Object References and Memory Concepts
In Java, a variable declared with a class type generally holds a reference to an object rather than containing the complete object itself.
Example
class Laptop {
String brand;
}
public class Main {
public static void main(String[] args) {
Laptop laptop1 = new Laptop();
laptop1.brand = "Dell";
Laptop laptop2 = laptop1;
laptop2.brand = "Lenovo";
System.out.println(laptop1.brand);
System.out.println(laptop2.brand);
}
}
Output
Lenovo
Lenovo
Both variables refer to the same object. Therefore, changing the object's brand through laptop2 is visible when accessing it through laptop1.
If a separate object is created with new Laptop(), it has its own independent instance fields.
Important Reference Concepts
- Two reference variables may refer to the same object.
- Assigning one reference variable to another does not automatically clone the object.
- A reference can be
null, meaning it does not currently refer to an object.
- Calling an instance method through a null reference causes a
NullPointerException.
- Objects that are no longer reachable may eventually be reclaimed by the garbage collector.
15. Comparing Objects
Java provides different ways to compare references and object values. The == operator compares object references, while equals() can compare logical equality when a class implements it appropriately.
Example
class Product {
String name;
Product(String name) {
this.name = name;
}
}
public class Main {
public static void main(String[] args) {
Product p1 = new Product("Mouse");
Product p2 = new Product("Mouse");
Product p3 = p1;
System.out.println(p1 == p2);
System.out.println(p1 == p3);
}
}
Output
false
true
The first comparison is false because p1 and p2 refer to separate objects. The second is true because both variables refer to the same object.
For value-based equality, classes should implement equals() and hashCode() consistently where appropriate. Simply using equals() on a custom class that does not override it generally compares references through the inherited implementation.
16. Organizing Classes into Separate Files
In practical applications, classes are often stored in separate source files to make code easier to maintain and reuse. A public top-level class is normally declared in a file with the same name as that class.
Student.java
public class Student {
private String name;
public Student(String name) {
this.name = name;
}
public void display() {
System.out.println("Student: " + name);
}
}
Main.java
public class Main {
public static void main(String[] args) {
Student student = new Student("Neha");
student.display();
}
}
Compile and Run
javac Student.java Main.java
java Main
Output
Student: Neha
This organization makes the Student class reusable in other parts of the application. In larger projects, packages can also group related classes into logical namespaces.
17. Common Errors When Implementing Classes and Objects
| Error |
Why It Happens |
Solution |
| Cannot find symbol |
A class, field, or method name is misspelled or unavailable. |
Check spelling, scope, imports, and declarations. |
| NullPointerException |
An instance member is accessed through a null reference. |
Initialize the reference or check for null where appropriate. |
| Constructor mismatch |
The supplied arguments do not match an available constructor. |
Check parameter types, order, and constructor declarations. |
| Non-static member referenced from a static context |
An instance member is accessed without an object in a static context. |
Create an instance or redesign the member as static when appropriate. |
| Private access error |
Code outside the declaring class tries to access a private member. |
Use a suitable public method or revise the class design. |
| Unexpected shared data |
A static field is used when separate values are needed per object. |
Use an instance field for object-specific state. |
| Invalid object state |
Fields accept values that violate application rules. |
Validate inputs in constructors and mutator methods. |
18. Best Practices for Classes and Objects
- Use meaningful names: Choose names such as
Student, BankAccount, and calculateTotal().
- Follow naming conventions: Use PascalCase for class names and camelCase for variables and methods.
- Keep fields private: Expose only the access needed by other classes.
- Initialize objects correctly: Use constructors to establish valid initial state.
- Validate inputs: Prevent invalid data from entering the object.
- Keep methods focused: Each method should perform a clear and well-defined task.
- Avoid unnecessary static fields: Use static fields for class-level data, not for values that differ between objects.
- Reduce duplication: Place reusable logic in methods rather than copying it repeatedly.
- Prefer clear class responsibilities: A class should have a cohesive purpose.
- Use comments thoughtfully: Explain complex decisions rather than repeating what obvious code already says.
- Test object behavior: Check valid inputs, invalid inputs, and important boundary conditions.
19. Mini Project: Student Record Management
Build a small program that stores student information, calculates a grade based on marks, and displays the record. This project combines fields, constructors, methods, validation, and object creation.
Project Requirements
- Create a Student class with name, roll number, and marks.
- Initialize the fields using a constructor.
- Reject marks outside the range of 0 to 100.
- Create a method to determine a grade.
- Create a method to display the student's details.
- Create at least three Student objects with different data.
Sample Implementation
class Student {
private String name;
private int rollNumber;
private double marks;
Student(String name, int rollNumber, double marks) {
if (name == null || name.isBlank()) {
throw new IllegalArgumentException("Name is required.");
}
if (rollNumber <= 0) {
throw new IllegalArgumentException(
"Roll number must be positive."
);
}
if (marks < 0 || marks > 100) {
throw new IllegalArgumentException(
"Marks must be between 0 and 100."
);
}
this.name = name;
this.rollNumber = rollNumber;
this.marks = marks;
}
String calculateGrade() {
if (marks >= 90) {
return "A";
} else if (marks >= 75) {
return "B";
} else if (marks >= 60) {
return "C";
} else if (marks >= 40) {
return "D";
} else {
return "F";
}
}
void displayRecord() {
System.out.println("Name: " + name);
System.out.println("Roll Number: " + rollNumber);
System.out.println("Marks: " + marks);
System.out.println("Grade: " + calculateGrade());
System.out.println("--------------------");
}
}
public class Main {
public static void main(String[] args) {
Student s1 = new Student("Aarav", 101, 91);
Student s2 = new Student("Meera", 102, 78);
Student s3 = new Student("Kabir", 103, 56);
s1.displayRecord();
s2.displayRecord();
s3.displayRecord();
}
}
Sample Output
Name: Aarav
Roll Number: 101
Marks: 91.0
Grade: A
--------------------
Name: Meera
Roll Number: 102
Marks: 78.0
Grade: B
--------------------
Name: Kabir
Roll Number: 103
Marks: 56.0
Grade: D
--------------------
The grade boundaries in this example are illustrative and can be changed to match a school's grading policy.
20. Practice Exercises
- Car Class: Create a Car class with brand, model, and year. Add a method that displays all details.
- Rectangle Calculator: Create two Rectangle objects with different dimensions and calculate their area and perimeter.
- Employee Salary: Create an Employee class with employee ID, name, and monthly salary. Add methods to calculate annual salary and display the record.
- Bank Account: Implement deposit and withdrawal operations while preventing negative amounts and withdrawals beyond the available balance.
- Product Inventory: Create a Product class with name, price, and quantity. Add a method to calculate inventory value.
- Book Library: Create a Book class with title, author, and availability. Add methods to borrow and return a book.
- Constructor Overloading: Create a class with a no-argument constructor and a parameterized constructor.
- Object Comparison: Create two objects with identical field values and compare their references and logical values.
- Encapsulation: Make fields private and implement getters and validated setters where suitable.
- Student Records: Extend the mini project to store students in an array or collection and display their grades.
21. Interview Questions and Answers
Q1. What is a class in Java?
Answer: A class is a blueprint that defines the fields, constructors, and methods used to represent and operate on objects.
Q2. What is an object?
Answer: An object is an instance of a class. It has identity, state, and behavior.
Q3. What is the difference between a class and an object?
Answer: A class defines the structure and behavior, while an object is a concrete instance created from that definition.
Q4. How do you create an object in Java?
Answer: A common way is to use the new keyword, as in Student student = new Student();, provided a matching constructor is available.
Q5. What is a constructor?
Answer: A constructor initializes a newly created object. It has the same name as the class and has no return type.
Q6. What is the purpose of the this keyword?
Answer: The this keyword refers to the current object. It is commonly used to distinguish instance fields from parameters with the same names.
Q7. What is the difference between instance and static variables?
Answer: Each object has its own copy of an instance field, while a static field is associated with the class and shared at the class level.
Q8. What is encapsulation?
Answer: Encapsulation combines data and related behavior while controlling access to internal state, commonly through private fields and public methods.
Q9. What happens when one object reference is assigned to another?
Answer: Both variables refer to the same object. Changes to that object's mutable state are visible through either reference.
Q10. What is the difference between == and equals() for objects?
Answer: The == operator compares object references. The equals() method can compare logical values if the class implements value equality.
Q11. Can a class have multiple constructors?
Answer: Yes. Constructor overloading allows multiple constructors with different parameter lists.
Q12. Why should fields often be private?
Answer: Private fields help prevent uncontrolled changes and allow the class to validate data through controlled methods.
Q13. What is a NullPointerException?
Answer: It is a runtime exception that occurs when code performs an operation requiring an object through a null reference.
Q14. Can two objects of the same class have different values?
Answer: Yes. Each object has its own instance fields, so two objects created from the same class can store different data.
Q15. What makes a good class design?
Answer: A good class has a clear responsibility, meaningful names, controlled access to state, appropriate validation, focused methods, and limited unnecessary duplication.
22. Quick Revision Checklist
- A class defines the structure and behavior of objects.
- An object is an instance of a class.
- The
new keyword is commonly used to create objects.
- Fields store state; methods define behavior.
- Constructors initialize newly created objects.
- The
this keyword refers to the current object.
- Instance fields hold object-specific values.
- Static fields represent class-level data.
- Encapsulation controls access to internal state.
- Reference variables can refer to the same object.
== compares references; equals() can compare logical values.
- Validation helps prevent invalid object states.
- Separate source files and packages help organize larger Java applications.
23. Conclusion
Implementing classes and objects through practical examples is an essential step in learning Core Java and Object-Oriented Programming. Classes help organize data and behavior, while objects allow programs to represent individual entities such as students, employees, products, bank accounts, and geometric shapes.
By practicing constructors, instance fields, methods, encapsulation, object references, validation, and reusable class design, learners can build a strong foundation for larger Java applications. Continue practicing by creating small programs, testing different objects, and gradually combining multiple classes into a complete application.
To explore more Core Java concepts, visit the Core Java Training course, register through the course demo registration page, or explore the JustAcademy website.